package com.qiangqiang.task.server.service;


import com.qiangqiang.task.server.consts.AchievementConst;
import com.qiangqiang.task.server.consts.TimeConst;
import com.qiangqiang.task.server.dto.CommentsDTO;

import com.qiangqiang.task.server.dto.PostDTO;
import com.qiangqiang.task.server.entity.Comments;
import com.qiangqiang.task.server.entity.Message;
import com.qiangqiang.task.server.mapper.CommentsMapper;
import com.qiangqiang.task.server.mapper.MessageMapper;
import com.qiangqiang.task.server.mapper.PostMapper;
import com.qiangqiang.task.server.util.SnowflakeIdWorker;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: task
 * @description:
 * @author: Sky.lin
 * @create: 2018-12-27 16:46
 **/
@Service
public class CommentsService extends BaseService {

    @Autowired
    CommentsMapper commentsMapper;

    @Autowired
    RankingService rankingService;

    @Autowired
    NotificationService notificationService;

    @Autowired
    PostMapper postMapper;

    @Autowired
    MessageMapper messageMapper;

    SnowflakeIdWorker commentsWorker = new SnowflakeIdWorker(0, 4);

    SnowflakeIdWorker messageWorker = new SnowflakeIdWorker(0, 8);


    public boolean addComments(Comments comments) {
        // 改变用户的成就值,发布一个评论获得 1 成就值
        rankingService.changeRanking(comments.getFromId(), AchievementConst.commentValue);

        // 持久化评论
        comments.setCommentsId(commentsWorker.nextId());
        comments.setCreateTime(Instant.now().toEpochMilli());
        comments.setUpdateTime(Instant.now().toEpochMilli());
        commentsMapper.insertComments(comments);

        // 发送通知
        PostDTO postDTO = beanToDTO(postMapper.queryPostByPostId(comments.getPostId()));
        notificationService.notifyUser(comments.getFromId(), postDTO.getPublisherId(), String.valueOf(postDTO.getPostId()), postDTO);

        // 持久化通知
        Message message = new Message();
        message.setCommonId(postDTO.getPostId());
        message.setContent(comments.getContent());
        message.setFromId(comments.getFromId());
        message.setToId(postDTO.getPublisherId());
        message.setMessageId(messageWorker.nextId());
        message.setType(1);
        message.setCreateTime(TimeConst.nowTimeMilli);
        message.setUpdateTime(TimeConst.nowTimeMilli);
        messageMapper.insertMessage(message);
        return true;
    }

    public List<CommentsDTO> findAllComments(int page, int pageSize, long postId) {
        return commentsMapper.queryAllPost(page, pageSize, postId).stream().
                map(this::beanToDTO).collect(Collectors.toList());
    }
}
